package com.csthink.common.infrastructure.util;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import static com.csthink.common.infrastructure.constant.Constants.TRACE_ID;

/**
 * @author <a href="mailto:security.2009@live.cn">Mars</a>
 * @since 2023-09-14
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class TrackingUtil {

    public static String generate() {
        return IDGenerator.getId();
    }

    public static String getFromCurThread() {
        return StringUtils.defaultString(MDC.get(TRACE_ID), generate());
    }

    public static String setIfNotExist() {
        String trackingId = MDC.get(TRACE_ID);
        if (StringUtils.isBlank(trackingId)) {
            trackingId = generate();
            MDC.put(TRACE_ID, trackingId);
        }

        return trackingId;
    }

    public static void setIfNotExist(String trackingId) {
        if (StringUtils.isBlank(MDC.get(TRACE_ID))) {
            MDC.put(TRACE_ID, ObjectUtils.defaultIfNull(trackingId, generate()));
        }
    }

    public static void setTraceId(String traceId) {
        MDC.put(TRACE_ID, ObjectUtils.defaultIfNull(traceId, generate()));
    }

    public static void clearTraceId() {
        MDC.remove(TRACE_ID);
    }
}
